<?php

namespace App\Http\Controllers\V1\Admin;

use App\Http\Controllers\V1\Api\BaseController;
use App\Models\V1\Admins;
use App\Models\V1\SysLoginLogs;
use Earnp\GoogleAuthenticator\GoogleAuthenticator;
use Illuminate\Http\Request;

class AuthController extends BaseController
{
    /**
     * 管理员登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {

        $security_code=$request->input('security_code',"");
        $username=$request->input('username',"");

        //查询账号是否启用安全动态密码
        $credentials = $request->only(['username', 'password']);

        if (! $token = auth('box_admin')->attempt($credentials)) {

            return ajax_output(300,"用户名或密码错误");
        }

        $user=auth('box_admin')->user();

       $exists =  Admins::where('username',$username)->where('state',0)->exists();

       if($exists) {
           return ajax_output(300,"用户名不存在或被禁用");
       }


        //更新登录表token
        auth('box_admin')->user()->setRememberToken($token);
        //记录日志
        $loginlogs_model=new SysLoginLogs();
        $loginlogs_model->create(
            [
                'admin_id'=>$user->id,
                'user_name'=>$user->username,
                'ip'=>$request->getClientIp(),
                'login_location'=>"中国,天津",
                'browser'=>"chrome",
                'os'=>"MAC",
                'state'=>1,
                'msg'=>""
            ]
        );
        return ajax_output(200,"成功",['token'=>$token,'id'=>$user->id]);
    }


    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        if(auth('box_admin')->user()){
            auth('box_admin')->logout();
        }
        return ajax_output(200,"成功");
    }
}
